package com.ramos.kuaixiao.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.ramos.kuaixiao.entity.BrandKeywords;

import java.util.ArrayList;
import java.util.List;

public class BrandKeywordsDB {
    private static String TAG = "BrandKeywordsDB";
    private static String TABLE_NAME = "BrandKeywords";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
        CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "pkey" + "  CHAR(50) PRIMARY KEY NOT NULL,"
                + "dealer_id" + " CHAR(30)," + "brand_id" + " CHAR(30)," + "keyword" + " CHAR(50)," + "sub_keyword" + " CHAR(50)," + "modify_time" + " Long);";
        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    public int addAll(List<BrandKeywords> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM BrandKeywords");
        String sql = "insert into BrandKeywords(pkey,dealer_id,brand_id,keyword,sub_keyword,modify_time) values(?,?,?,?,?,?)";
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        SQLiteStatement stmt = db.compileStatement(sql);
        for (int i = 0; i < customer.size(); i++) {
            stmt.bindString(1, customer.get(i).getPkey() + "");
            stmt.bindString(2, customer.get(i).getDealer_id() + "");
            stmt.bindString(3, customer.get(i).getBrand_id() + "");
            stmt.bindString(4, customer.get(i).getKeyword() + "");
            stmt.bindString(5, customer.get(i).getSub_keyword() + "");
            stmt.bindString(6, customer.get(i).getModify_time() + "");
            stmt.execute();
            stmt.clearBindings();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public int updateAllKeywords(List<BrandKeywords> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        Log.d(TAG, "updateAllKeywords:" + customer.size());
        for (int i = 0; i < customer.size(); i++) {
            BrandKeywords keywords = customer.get(i);
            if (hasKeywords(keywords.getPkey() + "")) {
                ContentValues cv = new ContentValues();
                cv.put("dealer_id", keywords.getDealer_id() + "");
                cv.put("brand_id", keywords.getBrand_id() + "");
                cv.put("keyword", keywords.getKeyword() + "");
                cv.put("sub_keyword", keywords.getSub_keyword() + "");
                cv.put("modify_time", keywords.getModify_time() + "");
                int n = db.update("BrandKeywords", cv, "pkey=?", new String[]{keywords.getPkey() + ""});
                Log.d(TAG, "updateAllKeywords:" + keywords.getPkey() + " " + n);
            } else {
                ContentValues cv = new ContentValues();
                cv.put("pkey", keywords.getPkey() + "");
                cv.put("dealer_id", keywords.getDealer_id() + "");
                cv.put("brand_id", keywords.getBrand_id() + "");
                cv.put("keyword", keywords.getKeyword() + "");
                cv.put("sub_keyword", keywords.getSub_keyword() + "");
                cv.put("modify_time", keywords.getModify_time() + "");
                long n = db.insert("BrandKeywords", null, cv); //如果有记录，则更新，并返回1，否则返回0
                Log.d(TAG, "insertAllKeywords:" + keywords.getPkey() + " " + n);
            }
            // 生成的sql是 INSERT INTRO OR REPLACE INTO 这样的 (如果存在就替换存在的字段值. 存在的判断标准是主键冲突, 这里的主键是userId). 下面会介绍这个地方的方法
            //db.insertWithOnConflict("StoreNum",null, cv, SQLiteDatabase.CONFLICT_REPLACE) ; //如果有记录，则更新，并返回1，否则返回0
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public boolean hasKeywords(String pkey) {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from BrandKeywords where pkey = ?", new String[]{pkey});
        if (cursor.getCount() > 0) {
            cursor.close();
            Log.d(TAG, "hasKeywords true");
            return true;
        } else {
            Log.d(TAG, "hasKeywords false");
            cursor.close();
            return false;
        }
    }

    public List<BrandKeywords> findAll() {
        List<BrandKeywords> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from BrandKeywords", new String[]{});
        Log.d(TAG, "cursor:" + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            BrandKeywords customer = new BrandKeywords();
            customer.setDealer_id(cursor.getString(1));
            customer.setBrand_id(cursor.getString(2));
            customer.setKeyword(cursor.getString(3));
            customer.setSub_keyword(cursor.getString(4));
            list.add(customer);
        }
        cursor.close();
        Log.d(TAG, "findAllBrandKeywords:" + list.size());
        return list;
    }

    public long getMaxModifyTime() {
        long param = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select max(modify_time)from BrandKeywords ", new String[]{});
        Log.d(TAG, "getMaxModifyTime:getCount" + cursor.getCount());
        if (cursor.moveToFirst()) {
            param = cursor.getLong(0);
        }
        cursor.close();
        Log.d(TAG, "getMaxModifyTime:param" + param);
        return param;
    }

    public void deleteAll() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM BrandKeywords");
        Log.d(TAG, "deleteAllBrandKeywords ");
    }

    public boolean hasData() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from BrandKeywords", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "hasBrandKeywords true");
            return true;
        } else {
            Log.d(TAG, "hasBrandKeywords false");
            cursor.close();
            return false;
        }
    }

}
